﻿using Common;
using DotNetCore.CAP;
using DB.Model;
using DB.MongoDB;
using Log4_Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NoticeCorpWechat.interfaces;
using NoticeCorpWechat.postdata;
using NoticeCorpWechat.result;
using NoticeWechat;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NoticeWechatApi.Subscribe
{
    public class MessageJobSubscribe : ICapSubscribe
    {

        IMongoDbHelper<Tasks> _Db; IMongoDbHelper<User> _DbUser;
        IAccessTokenHelper _AccessTokenHelper; IMessageHelper _IMessageHelper;
        private ILogger _logger = null;
        public MessageJobSubscribe(IMongoDbHelper<Tasks> mongoDb, IMongoDbHelper<User> DbUser, IMessageHelper IMessageHelper, IAccessTokenHelper AccessTokenHelper, ILogHelper _ILogHelper)
        {
            _Db = mongoDb;
            _DbUser = DbUser;
            _AccessTokenHelper = AccessTokenHelper;
            _IMessageHelper = IMessageHelper;
            _logger = _ILogHelper.GetLogger<MessageJobSubscribe>();
        }

         
        [CapSubscribe("WeChatTextMessage")]
        public async Task<bool> WeChatTextReceivedMessage(string[] ids)
        {
            try
            {
                var id = ids[0]; string Content = null;
                if (ids.Length > 1)
                    Content = ids[1];
                var i = await _Db.QueryOne(id);
                if (i != null)
                {
                    var one = await _DbUser.QueryOne(i.UserId);
                    if (one == null) return false;
                    //if (one.UseTimes >= one.Times) return false;
                    var token = one.Access_token;
                    if (DateTime.Now.AddMinutes(10) >= one.Expires_in)
                    {
                        var result = _AccessTokenHelper.Get_AccessToken(one.CorpId, one.CorpSecret);
                        if (result.IsNullOrEmpty()) { return false; }
                        var res = result.JsonToObject<TokenResult>();
                        if (res.errcode == (int)EnumResult.成功)
                        {
                            one.Expires_in = DateTime.Now.AddSeconds(res.expires_in);
                            one.Access_token = res.access_token;
                            token = one.Access_token;
                            await _DbUser.Update(one);
                        }
                    }
                    var sendObj = new MessageTextPost()
                    {
                        touser = i.Received,
                        agentid = one.AgentId.ToInt(),
                        text = new TextContent() { content = Content.IsNullOrEmpty() ? i.Content : Content }
                    };

                    var resultw = await _IMessageHelper.Send(token, sendObj.ToJson());
                    if (resultw == EnumResult.重试)
                    {
                        var result = _AccessTokenHelper.Get_AccessToken(one.CorpId, one.CorpSecret);
                        if (result.IsNullOrEmpty()) { return false; }
                        var res = result.JsonToObject<TokenResult>();
                        if (res.errcode == 0)
                        {
                            one.Expires_in = DateTime.Now.AddSeconds(res.expires_in);
                            one.Access_token = res.access_token;
                            token = one.Access_token;
                            await _DbUser.Update(one);
                        }
                        resultw = await _IMessageHelper.Send(token, sendObj.ToJson());
                    }
                    if (resultw == EnumResult.成功)
                        await _Db.Modify(i.Id.ToString(), "Status", "1");

                    //更新user 
                    await _DbUser.Modify(one.Id.ToString(), "UseTimes", (one.UseTimes++).ToString());
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message + ex.StackTrace);
                return false;
            }
            return true;
        }
    }
}
